package sys

import (
	"gitee.com/dayu1985/can_api/controller/base"
	"github.com/gin-gonic/gin"
	"path"
	"strings"
	"net/http"
	"io"
	"gitee.com/dayu1985/can_api/service"
	"gitee.com/dayu1985/can_api/errors"
)

/*************************************************
 *	@author zander
 *	@time 	2018年2月3日14:45:24
 *	@brief 	APP应用系统类接口
 *************************************************/

//APP系统接口
func Resource(context *base.RouteContext) {
	r := context.Privilege.AppResource
	pub := context.Privilege.Public

	r.StaticFS("/doc",base.HTTPBox["doc"])
	r.StaticFS("/img/index",base.HTTPBox["img_index"])
	r.StaticFS("/third",base.HTTPBox["thirddata"])
	r.StaticFS("/map",base.BoxStr["map"])
	r.StaticFS("/download",base.HTTPBox["appdownload"])

	pub.StaticFS("/static",base.BoxStr["static"])

	//资源文件动态读取
	sysService := service.NewSysService()
	context.Privilege.Public.GET("/upload/:name", func(ctx *gin.Context) {
		name := ctx.Param("name")
		filenameWithSuffix := path.Base(name)      //获取文件名带后缀
		fileSuffix := path.Ext(filenameWithSuffix) //获取文件后缀
		name = strings.TrimSuffix(name, fileSuffix)

		f, err := sysService.File.Get(name)

		b := make([]byte, 512)
		f.Read(b)
		mime := http.DetectContentType(b)
		f.Seek(0, io.SeekStart)

		if err != nil {
			base.Fail(ctx,errors.FsNotFoundErr())
			return
		}

		ctx.Header("Content-Type", mime)
		io.Copy(ctx.Writer, f)
	})
}

func init() {
	base.Register(Resource)
}
